<?php

namespace App\Http\Controllers\Api\Love;

use App\Models\Love\LoveInfo;
use App\Models\Love\LoveOrderLog;
use App\Models\Love\LovePayLog;
use App\User;
use App\UserCoinLog;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use Mockery\CountValidator\Exception;

class LoveController extends Controller
{
    const bussiness_id = 10;        // 找情人

    protected $wechat;

    public function __construct()
    {
        $this->wechat = app('wechat');
    }

    /**
     * @function 获取用户个人信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserInfo()
    {
        $user = auth()->user();
        $user = User::find(1);
        $data = [];

        $data['XYB'] = $user->XYB;
        $data['avatar'] = $user->avatar;
        $data['nickname'] = $user->nickname;
        $data['sex'] = $user->sex;
        $data['isWechatExist'] = $user->game_love ? 1 : 0;

        return response()->json([
            'code' => 0,
            'msg' => '获取个人信息成功',
            'data' => $data
        ]);

    }

    /**
     * @function 写入微信号
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function setWechatAccout(Request $request)
    {

        $input = $request->all();

        $rules = ['wechatNumber' => array('required', 'regex: /^[a-zA-Z0-9_]{0,}$/')];

        $messages = [
            'wechatNumber.required' => "微信号不能为空",
            'wechatNumber.regex' => '微信号格式不正确'
        ];

        $validator = Validator::make($input, $rules, $messages);

        if ($validator->fails()) {

            return response()->json([
                'code' => 1,
                'msg' => $validator->errors()->first()

            ]);
        }

        $user = auth()->user();
        $user=User::find(1);
        //插入数据
        try {

            $loveInfo = new LoveInfo();
            $loveInfo->user_id = $user->id;
            $loveInfo->wechat_accout = $input['wechatNumber'];
            $loveInfo->sex = $user->sex;
            $loveInfo->save();

            $code=0;
            $msg='请求成功';

        } catch (\Exception $e) {

            $code=1;
            $msg='请勿频繁操作';

        }

        return response()->json([
            'code' => $code,
            'msg' => $msg,
        ]);
    }

    /**
     * @function 获取微信号列表
     * @return mixed
     */
    public function getWechatList()
    {

        $usersInfo = DB::table('game_love_info')
            ->join('user', 'user.id', '=', 'game_love_info.user_id')
            ->select('user.avatar', 'game_love_info.wechat_accout')
            ->take(10)->get();

        return response()->json([

            'code' => 0,
            'msg' => '列表获取成功',
            'data' => $usersInfo

        ]);
    }


    /**
     * @function 下单
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function handle(Request $request)
    {

        $input = $request->all();

        $rules = ['face' => 'required', 'sex' => 'required', 'gold' => 'required'];

        $messages = [
            'face.required' => "投注种类不能为空",
            "sex.required" => "性别不能为空",
            "gold.required" => "投注金额不能为空"
        ];

        $validator = Validator::make($input, $rules, $messages);

        if ($validator->fails()) {

            return response()->json([
                'code' => 1,
                'msg' => '非法请求数据',
                'data' => $validator->errors()->all()
            ]);
        }

        $face = $request->input('face');    /* 1-美，2-丑 */
        $gold = $request->input('gold');    //不能大于10000
        $sex = $request->input('sex');  //性别 1男，2女

        $user = auth()->user();
        $user = User::find(1);
        //下单金额不能大于100

        $gold = abs(intval($gold));
        if ($gold > 100) {

            return response()->json([
                'code' => 1,
                'msg' => '最多只能下注10000小妖币'
            ]);

        }

        //检查小妖币是否充足
        $XYB = UserCoinLog::totalXyb($user->id);


        if ($XYB < $gold) {
            return response()->json([
                'code' => 1,
                'msg' => '用户余额不足'
            ]);
        }

        // 限定操作频次

        $key = "love:handle:$user->id";


        $redis = new \Redis();
        $redis->connect(env('REDIS_HOST'), env('REDIS_PORT'));
        $redis->auth(env('REDIS_PASSWORD'));

        if (!$redis->set($key, 'Y', array('nx', 'px' => 1000))) {

            return response()->json([
                'code' => 1,
                'msg' => '您的操作过于频繁，请稍后再试'
            ]);

        }

        //增加历史获利的统计

        if (LovePayLog::where('user_id', $user->id)->sum('add_XYB') >= 500) {

            //发出警报
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, "http://sms-api.luosimao.com/v1/send_batch.json");
            curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_0);
            curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 8);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
            curl_setopt($ch, CURLOPT_HEADER, FALSE);
            curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
            curl_setopt($ch, CURLOPT_USERPWD, 'api:key-5145112f10b704bbd5592f80402c77b5');
            curl_setopt($ch, CURLOPT_POST, TRUE);
            curl_setopt($ch, CURLOPT_POSTFIELDS, array('mobile_list' => '13726873311,13632403818,13627240119', 'message' => '你好，发现异常情况。项目：找情人，UID：' . $user->id . '，描述：用户通过游戏获利超过500元。【小妖传媒】'));

            $res = curl_exec($ch);

            return response()->json([

                'code' => 1,
                'msg' => '请勿频繁操作'

            ]);
        }


        //下单
        try {

            $data = [];
            $awardGold = 0;//用户获奖金额

            $now = time();

            //【重要】下面重复提交限制使用了第二个参数$now

            $key = $user->id . '-' . $now . '-' . $face . '-' . $gold;

            //记录下单记录
            try {

                $orderLogModel = new LoveOrderLog();
                $orderLogModel->user_id = $user->id;
                $orderLogModel->gold = $gold;
                $orderLogModel->key = $key;
                $orderLogModel->face = $face;
                $orderLogModel->save();
                $orderLogId = $orderLogModel->id;

            } catch (\Exception $e) {

                throw new \Exception('下单错误，请勿重复提交', 1);

            }

            //查询上一次下单时间

            $preOrderLogItemArr = LoveOrderLog::where('id', '<', $orderLogId)->where('user_id', $user->id)->orderBy('id', 'desc')->limit(1)->get()->toArray();

            if (!empty($preOrderLogItemArr[0])) {

                $keyParts = explode('-', $preOrderLogItemArr[0]['key']);
                $preOrderAddMicrotime = $keyParts[1];

                if ($now - $preOrderAddMicrotime < config('love.time_limit')) {  //上一次下单时间比下单停顿时间短，认为并发

                    LoveOrderLog::find($orderLogId)->forceDelete();
                    throw new \Exception("请勿重复提交", 1);

                }

            }

            DB::beginTransaction();

            $user->XYB = UserCoinLog::totalXyb($user->id);

            //记录扣款日志
            $payLogModel = new LovePayLog();
            $payLogModel->user_id = $user->id;
            $payLogModel->from_XYB = $user->XYB;
            $payLogModel->add_XYB = -$gold;
            $payLogModel->to_XYB = $user->XYB - $gold;
            $payLogModel->order_id = $orderLogId;
            $payLogModel->add_time = $now;
            $payLogModel->update_time = $now;
            $payLogModel->save();

            //扣减用户余额
            //config/type.php    14 => '找情人下单'
            $key = '14-' . $user->id . '-' . -$gold . '-' . $now;

            //business表  10 => 找情人
            $data = UserCoinLog::log(10, $user->id, UserCoinLog::TYPE_XYB, -$gold, '找情人下单消耗', $key);

            //用户玩游戏状态更新
            $user->update(['status' => DB::raw('status|4')]);

            if (UserCoinLog::totalXyb($user->id) < 0) {
                throw new \Exception('小妖币不足，请充值', 1);
            }

            //随机出开奖结果
            $win = $this->get_rand();

            if ($win == (int)$face) {//用户中奖

                //奖励金额
                $awardGold = $gold * config('love.award_times');

                //获取用户最新小妖币
                $user->XYB = UserCoinLog::totalXyb($user->id);

                //记录奖励
                $payLogModel = new LovePayLog();
                $payLogModel->user_id = $user->id;
                $payLogModel->from_XYB = $user->XYB;
                $payLogModel->add_XYB = $awardGold;
                $payLogModel->to_XYB = $user->XYB + $gold;
                $payLogModel->order_id = 0;
                $payLogModel->add_time = $now;
                $payLogModel->update_time = $now;
                $payLogModel->save();

                //config/type.php    14 => '找情人下单'
                $key = '14-' . $user->id . '-' . $awardGold . '-' . $now;

                //business表  10 => 找情人
                UserCoinLog::log(10, $user->id, UserCoinLog::TYPE_XYB, $awardGold, '找情人开奖奖励', $key);


                //获取用户信息
                $user->XYB = UserCoinLog::totalXyb($user->id);

                $code = 0;
                $msg = "用户中奖";
                $data = $user;

            } else {

                //用户未中奖
                $user->XYB = UserCoinLog::totalXyb($user->id);

                //定义返回值
                $code = -1;
                $msg = "用户未中奖";
                $data = $user;

            }


            DB::commit();


        } catch (\Exception $e) {

            DB::rollBack();
            $code = 1;
            $msg = $e->getMessage();
        }

        //获取随机微信号
        $wechat = DB::table('game_love_info')->where('sex', '!=', $sex)->get()->toArray();

        if (empty($wechat)) {

            return response()->json([
                'code' => 1,
                'msg' => "网络错误，请刷新页面重新载入"
            ]);

        }
        shuffle($wechat);

        $wechatArr = array_pop($wechat);

        return response()->json([
            'code' => $code,
            'msg' => $msg,
            'XYB' => $data->XYB,
            'awardGold' => $awardGold,
            'wechat' => $wechatArr->wechat_accout
        ]);

    }

    /**
     * @function 获取随机抽奖结果
     * @return int
     */
    private function get_rand()
    {
        $rands = rand(1, 10);

        if ($rands <= 5) {
            $num = 1;
        } else {
            $num = 2;
        }

        return $num;

    }
}
